/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.Region;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class RegionService extends BaseService<Region> {

	@Autowired
	private UserService userService;

	public Region saveRegion(Region region, Integer userId) {
		
		if (region != null) {
			User user = userService.findById(userId);
			Region dbRegion = findById(region.getId());	
			if (dbRegion == null) {
				dbRegion = new Region();
				dbRegion.setCreatedBy(user);
				dbRegion.setCreationDate(DateUtil.getCurrentDate());
			}
			User regionalDirector = userService.findById(region.getRegionalDirector().getId());
			dbRegion.setRegionalDirector(regionalDirector);
			dbRegion.setDisplayName(region.getDisplayName());
			dbRegion.setUpdatedBy(user);
			dbRegion.setUpdationDate(DateUtil.getCurrentDate());
			return merge(dbRegion);
		}
		return null;
	}
	 
	public List<Region> findAllOrderBy(String columnName){
		String query = "from Region order by " + columnName +" ASC";
		return dao.getResultList(query);
	}
}
